package com.jeeplus.cms.util;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.jeeplus.cms.common.CmsConstant;
import com.jeeplus.cms.common.CmsProperties;
import com.jeeplus.common.utils.SpringContextHolder;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.core.mapper.JsonMapper;
import com.jeeplus.modules.cms.column.entity.CmsColumn;
import com.jeeplus.modules.cms.column.service.CmsColumnService;
import com.jeeplus.modules.cms.content.entity.CmsContents;
import com.jeeplus.modules.cms.content.service.CmsContentsService;
import com.jeeplus.modules.cms.contenttype.entity.CmsContentType;
import com.jeeplus.modules.cms.contenttype.service.CmsContentTypeService;
import com.jeeplus.modules.cms.dm.entity.CmsDynamic;
import com.jeeplus.modules.cms.dm.service.CmsDynamicService;
import com.jeeplus.modules.cms.dyn.entity.CmsContentsDyn;
import com.jeeplus.modules.cms.dyn.service.CmsContentsDynService;
import com.jeeplus.modules.cms.link.entity.CmsLink;
import com.jeeplus.modules.cms.link.service.CmsLinkService;
import com.jeeplus.modules.cms.model.entity.CmsModel;
import com.jeeplus.modules.cms.model.service.CmsModelService;
import com.jeeplus.modules.cms.site.entity.CmsSite;
import com.jeeplus.modules.cms.site.service.CmsSiteService;
import com.jeeplus.modules.cms.theme.entity.CmsThemes;
import com.jeeplus.modules.cms.theme.service.CmsThemesService;
import org.springframework.ui.Model;

import javax.servlet.ServletContext;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 内容管理工具类
 *
 * @author LiGuanHua
 * @version 2017-8-28
 */
public class CmsUtils {

    private static CmsSiteService siteService = SpringContextHolder.getBean(CmsSiteService.class);
    private static CmsThemesService themesService = SpringContextHolder.getBean(CmsThemesService.class);
    private static CmsLinkService linkService = SpringContextHolder.getBean(CmsLinkService.class);
    private static CmsColumnService columnService = SpringContextHolder.getBean(CmsColumnService.class);
    private static CmsContentTypeService contentTypeService = SpringContextHolder.getBean(CmsContentTypeService.class);
    private static CmsDynamicService dynamicService = SpringContextHolder.getBean(CmsDynamicService.class);
    private static CmsModelService modelService = SpringContextHolder.getBean(CmsModelService.class);
    private static CmsContentsService contentsService = SpringContextHolder.getBean(CmsContentsService.class);
    private static CmsContentsDynService contentsDynService = SpringContextHolder.getBean(CmsContentsDynService.class);
    private static ServletContext context = SpringContextHolder.getBean(ServletContext.class);


    public static final String UPDATE_EXPIRED_WEIGHT_TIME_CACHE = "UpdateExpiredWeightTime";
    public static final String UPDATE_EXPIRED_WEIGHT_TIME_TO_DYN_CACHE = "UpdateExpiredWeightTimeToDyn";
    public static final String UPDATE_EXPIRED_WEIGHT_TIME_TO_GUESTBOOK_CACHE = "UpdateExpiredWeightTimeToGuestbook";

    /**
     * 默认网站首页视图
     */
    public static final String DEFAULT_INDEX_VIEW = "frontIndex";

    /**
     * 当前栏目属性
     */
    public static final String CURRENT_COLUMN_ATTRIBUTE = "curColumn";

    /**
     * 当前栏目属性
     */
    public static final String CURRENT_MAIN_COLUMNID_ATTRIBUTE = "curMainColumnId";

    /**
     * 404错误视图路径
     */
    public static final String ERROR_VIEW_404 = "error/404";

    /**
     * 后端信息提示请求URL
     */
    public static final String MESSAGE_URL = SpringContextHolder.getBean(CmsProperties.class).getFrontPath() + "/common/message";

    /**
     * 不用发布内容的请求路径
     */
    public static final String CONTENT_NONE_URL = "none";

    /**
     * 链接模型英文名称
     */
    public static final String LINK_MODEL_ENNAME = "link";

    /**
     * 联系模型英文名称
     */
    public static final String CONTACT_MODEL_ENNAME = "contact";

    /**
     * 消息类型-信息
     */
    public static final String MESSAGE_TYPE_INFO = "info";

    /**
     * 消息类型-警告
     */
    public static final String MESSAGE_TYPE_WARNING = "warning";

    /**
     * 消息类型-危险
     */
    public static final String MESSAGE_TYPE_DANGER = "danger";

    /**
     * 主题参数配置前缀
     */
    public static final String THEMES_PARAM_CONFIG_PREFIX = "themesParamConfig_";

    /**
     * 栏目参数配置前缀
     */
    public static final String COLUMN_PARAM_CONFIG_PREFIX = "columnParamConfig_";

    /**
     * 动态表单key前缀
     */
    public static final String DYNAMIC_FORM_KEY_PREFIX = "k_";

    /**
     * Html5支持的Video媒体类型
     */
    public static final String HTML5_VIDEO_TYPE = ",mp4,m4v,webm,ogg,ogv,";

    /**
     * 主键分割器
     */
    private static final Splitter PRIMARY_KEY_SPLITTER = Splitter.on(",").trimResults().omitEmptyStrings();

    /**
     * 内容关键词分割器
     */
    private static final Splitter KEYWORDS_SPLITTER = PRIMARY_KEY_SPLITTER;

    /**
     * 按照点击数从大到小排序,点击数相同则按照序号从小到大排
     */
    private static final Comparator<CmsContents> HITS_COMPARATOR = (o1, o2) -> {
        final int firstColumnHits = null == o1.getHits() ? 0 : o1.getHits();
        final int firstColumnSort = null == o1.getSort() ? 0 : o1.getSort();
        final int secondColumnHits = null == o2.getHits() ? 0 : o2.getHits();
        final int secondColumnSort = null == o2.getSort() ? 0 : o2.getSort();
        return firstColumnHits != secondColumnHits ? (-1 * Integer.compare(firstColumnHits, secondColumnHits))
                : Integer.compare(firstColumnSort, secondColumnSort);
    };


    /**
     * 获取网站信息
     *
     * @return site or null
     */
    public static CmsSite getSite(String id) {
        List<CmsSite> siteList = CmsCacheUtils.getSiteListByCache();
        for (CmsSite site : siteList) {
            if (site.getId().equals(id)) {
                return site;
            }
        }
        return null;
    }

    /**
     * 获取网站主题
     *
     * @param siteId 网站id
     * @return CmsThemes or null
     */
    public static CmsThemes getSiteTheme(final String siteId) {
        if (org.apache.commons.lang3.StringUtils.isBlank(siteId)) {
            return null;
        }
        // 根据siteId找到对应的站点
        Optional<CmsSite> cmsSiteOptional = CmsCacheUtils.getSiteListByCache().stream().filter(site -> siteId.equals(site.getId())).findFirst();

        // 为了防止theme更新后站点信息缓存未更新，这里需要直接通过themeId查找主题
        return cmsSiteOptional.map(cmsSite -> null != cmsSite.getTheme() ? getThemeById(cmsSite.getTheme().getId()) : null)
                .orElseGet(() -> null);
    }

    /**
     * 获取指定数目的友情链接列表
     *
     * @param siteId    网站id
     * @param linkCount 友情链接数目
     */

    public static List<CmsLink> getLinkListByCache(final String siteId, final int linkCount) {
        List<CmsLink> result = CmsCacheUtils.getLinkListByCache(siteId)
                .stream()
                .filter(link -> siteId.equals(link.getSiteId()) && CmsConstant.YES.equals(link.getEnableFlag()))
                .collect(Collectors.toList());
        return result.size() <= linkCount ? result : result.subList(0, linkCount);
    }

    /**
     * 获取主栏目列表（一级栏目）
     *
     * @return list
     */
    public static List<CmsColumn> getMainColumnList(final String siteId) {
        if (org.apache.commons.lang3.StringUtils.isBlank(siteId)) {
            return Collections.emptyList();
        }

        // 根据siteId从栏目列表中筛选出一级栏目
        return CmsCacheUtils.getColumnListByCache(siteId).stream()
                .filter(item -> "0".equals(item.getParentId()) && siteId.equals(item.getSiteId()) && CmsConstant.YES.equals(item.getEnableFlag()))
                .collect(Collectors.toList());
    }

    /**
     * 获取栏目列表（二级栏目）
     *
     * @param parentId 父栏目编号
     * @return list
     */
    public static List<CmsColumn> getColumnList(final String siteId, final String parentId) {
        if (org.apache.commons.lang3.StringUtils.isBlank(parentId)) {
            return Collections.emptyList();
        }
        return CmsCacheUtils.getColumnListByCache(siteId).stream()
                .filter(column -> parentId.equals(column.getParentId()) && CmsConstant.YES.equals(column.getEnableFlag()))
                .collect(Collectors.toList());
    }

    /**
     * 根据栏目编号串获取栏目列表
     *
     * @param columnIds 栏目编号串
     * @return list
     */
    public static List<CmsColumn> getColumnListByIds(final String siteId, String columnIds) {
        String primaryKeyStr = org.apache.commons.lang3.StringUtils.trimToEmpty(columnIds);
        List<String> primaryKeyList = PRIMARY_KEY_SPLITTER.splitToList(primaryKeyStr);
        if (primaryKeyList.isEmpty()) {
            return Collections.emptyList();
        }

        // 为了提高查找的效率，这里将primaryKeyList转为map
        Map<String, String> primaryKeyMap = primaryKeyList.stream()
                .collect(Collectors.toMap(key -> key, value -> value, (v1, v2) -> v2));

        return CmsCacheUtils.getColumnListByCache(siteId).stream()
                .filter(column -> primaryKeyMap.containsKey(column.getId()) && CmsConstant.YES.equals(column.getEnableFlag()))
                .collect(Collectors.toList());
    }

    /**
     * 根据columnId获取CmsColumn
     *
     * @param columnId 栏目编号
     * @return CmsColumn or null
     */
    public static CmsColumn getColumnById(final String columnId) {
        if (org.apache.commons.lang3.StringUtils.isBlank(columnId)) {
            return null;
        }

        for (CmsSite site : CmsCacheUtils.getSiteListByCache()) {
            Optional<CmsColumn> optional = CmsCacheUtils.getColumnListByCache(site.getId())
                    .stream()
                    .filter(column -> columnId.equals(column.getId()) && CmsConstant.YES.equals(column.getEnableFlag()))
                    .findFirst();
            if (optional.isPresent()) {
                return optional.get();
            }
        }
        return null;
    }

    /**
     * 根据modelId获取model
     *
     * @param modelId 模型id
     * @return CmsModel or null
     */
    public static CmsModel getModelById(final String modelId) {
        if (org.apache.commons.lang3.StringUtils.isBlank(modelId)) {
            return null;
        }

        for (CmsSite site : CmsCacheUtils.getSiteListByCache()) {
            Optional<CmsModel> optional = CmsCacheUtils.getModelListByCache(site.getId())
                    .stream()
                    .filter(item -> modelId.equals(item.getId()) && CmsConstant.YES.equals(item.getEnableFlag()))
                    .findFirst();
            if (optional.isPresent()) {
                return optional.get();
            }
        }
        return null;
    }

    /**
     * 根据contentId获取CmsContents
     *
     * @param contentId 栏目编号
     * @return CmsContents or null
     */
    public static CmsContents getContentById(final String contentId) {
        if (org.apache.commons.lang3.StringUtils.isBlank(contentId)) {
            return null;
        }

        for (CmsSite site : CmsCacheUtils.getSiteListByCache()) {
            Optional<CmsContents> optional = CmsCacheUtils.getContentListByCache(site.getId())
                    .stream()
                    .filter(item -> contentId.equals(item.getId()))
                    .findFirst();
            if (optional.isPresent()) {
                return optional.get();
            }
        }
        return null;
    }

    /**
     * 根据contentId获取CmsContentDyn
     *
     * @param id 主键
     * @return CmsContentsDyn or null
     */
    public static CmsContentsDyn getContentDynById(final String id) {
        if (org.apache.commons.lang3.StringUtils.isBlank(id)) {
            return null;
        }

        for (CmsSite site : CmsCacheUtils.getSiteListByCache()) {
            Optional<CmsContentsDyn> optional = CmsCacheUtils.getContentDynListByCache(site.getId())
                    .stream()
                    .filter(item -> id.equals(item.getId()))
                    .findFirst();
            if (optional.isPresent()) {
                return optional.get();
            }
        }
        return null;
    }


    public static CmsContentType getContentTypeById(String id) {
        if (org.apache.commons.lang3.StringUtils.isBlank(id)) {
            return null;
        }

        for (CmsSite site : CmsCacheUtils.getSiteListByCache()) {
            Optional<CmsContentType> optional = CmsCacheUtils.getContentTypeListByCache(site.getId())
                    .stream()
                    .filter(item -> id.equals(item.getId()))
                    .findFirst();
            if (optional.isPresent()) {
                return optional.get();
            }
        }
        return null;
    }

    /**
     * 根据主题id获取主题
     *
     * @param themeId 主题id
     * @return CmsThemes or null
     */
    public static CmsThemes getThemeById(final String themeId) {
        if (org.apache.commons.lang3.StringUtils.isBlank(themeId)) {
            return null;
        }

        return CmsCacheUtils.getThemeListByCache()
                .stream()
                .filter(theme -> themeId.equals(theme.getId()) && CmsConstant.YES.equals(theme.getActiva()))
                .findFirst()
                .orElseGet(() -> null);
    }

    /**
     * 获取栏目内容分类列表
     *
     * @param columnId 栏目编号
     * @return list
     */
    public static List<CmsContentType> getContentTypeList(final String siteId, final String columnId) {
        if (org.apache.commons.lang3.StringUtils.isBlank(columnId)) {
            return Collections.emptyList();
        }
        return CmsCacheUtils.getContentTypeListByCache(siteId).stream()
                .filter(item -> null != item.getColumn() && columnId.equals(item.getColumn().getId()))
                .collect(Collectors.toList());
    }

    /**
     * 获取单例动态表单的数据（值）
     *
     * @param enName 动态表单模型英文名
     */
    @SuppressWarnings("unchecked")
    public static Map<String, Object> getDynamicDataOfSingleton(final String siteId, final String enName) {
        if (org.apache.commons.lang3.StringUtils.isBlank(enName)) {
            return new HashMap<>(16);
        }

        Optional<CmsDynamic> optional = CmsCacheUtils.getDynamicListByCache(siteId).stream()
                .filter(item -> enName.equals(item.getEnname()) && "1".equals(item.getType()) && CmsConstant.YES.equals(item.getLockFlag()))
                .findFirst();
        return JsonMapper.getInstance().fromJson(optional.orElseGet(CmsDynamic::new).getData(), Map.class);
    }

    /**
     * 获取联系模型栏目
     *
     * @return CmsColumn
     */
    public static CmsColumn getColumnOfContactModel(final String siteId) {
        if (org.apache.commons.lang3.StringUtils.isBlank(siteId)) {
            return new CmsColumn();
        }

        // 根据model获取对应的栏目
        List<CmsColumn> effectiveColumnList = CmsCacheUtils.getColumnListByCache(siteId);
        Optional<CmsColumn> contactColumnOptional = effectiveColumnList.stream().filter(cmsColumn -> {
            if (!siteId.equals(cmsColumn.getSiteId())) {
                return false;
            }

            // 获取模型
            if (null == cmsColumn.getModel() || null == cmsColumn.getModel().getId()) {
                return false;
            }
            CmsModel model = getModelById(cmsColumn.getModel().getId());
            if (null == model) {
                return false;
            }

            boolean isContactModelColumn = CmsUtils.CONTACT_MODEL_ENNAME.equals(model.getEnname());

            // 没有下级栏目
            return isContactModelColumn && !cmsColumn.getHasChildren();
        }).findFirst();
        return contactColumnOptional.orElseGet(CmsColumn::new);
    }

    /**
     * 判断是否Html5支持的video类型
     *
     * @param videoUrl video媒体URL
     * @return true or false
     */
    public static boolean isHtml5Video(String videoUrl) {
        String suffixName = videoUrl.substring(videoUrl.lastIndexOf(".") + 1).toLowerCase();
        return CmsUtils.HTML5_VIDEO_TYPE.contains("," + suffixName + ",");
    }

    /**
     * 获取推荐内容列表
     *
     * @param isPreview 是否预览
     * @param columnId  栏目ID，不为空则只获取本栏目推荐内容
     * @return list
     */
    public static List<CmsContents> getRecommendList(String siteId, String isPreview, final String columnId, String contentsId) {

        Integer recommendCount = null;

        // 更新过期权重
        contentsService.updateExpiredWeightToReq();

        Predicate<CmsContents> predicate = null;
        // 如果columnId不为空则需要增加栏目的判断
        if (org.apache.commons.lang3.StringUtils.isNotBlank(columnId)) {
            CmsColumn curColumn = getColumnById(columnId);
            String paramConfig = null != curColumn ? curColumn.getParamConfig() : "";
            paramConfig = org.apache.commons.lang3.StringUtils.defaultIfBlank(paramConfig, CmsUtils.getSiteTheme(siteId).getParamConfig());
            recommendCount = (Integer) CmsUtils.getParamConfig(CmsConstant.THEME_PARAM_RECOMMEND_COUNT_KEY, paramConfig);
            predicate = item -> {
                if (StringUtils.isNotBlank(contentsId) && item.getId().equals(contentsId)) {
                    return false;
                }
                if (!CmsConstant.YES.equals(item.getRecomFlag())) {
                    return false;
                }
                return columnId.equals(item.getColumnId());
            };
        } else {
            recommendCount = (Integer) CmsUtils.getParamConfig(CmsConstant.THEME_PARAM_RECOMMEND_COUNT_KEY, CmsUtils.getSiteTheme(siteId).getParamConfig());
            predicate = item -> {
                if (StringUtils.isNotBlank(contentsId) && item.getId().equals(contentsId)) {
                    return false;
                }
                return CmsConstant.YES.equals(item.getRecomFlag());
            };
        }

        if (recommendCount == null || recommendCount == 0) {
            recommendCount = CmsConstant.THEME_PARAM_RECOMMEND_COUNT_VAL;
        }

        List<CmsContents> contentsList = CmsCacheUtils.getContentListByCache(siteId).stream().filter(predicate).collect(Collectors.toList());
        return contentsList.size() > recommendCount ? contentsList.subList(0, recommendCount) : contentsList;
    }

    /**
     * 获取指定站点下的栏目关键字
     *
     * @param siteId   网站id
     * @param columnId 栏目ID，不为空则只获取本栏目推荐内容
     * @return list
     */
    public static List<String> getKeywordList(final String siteId, final String columnId) {
        if (org.apache.commons.lang3.StringUtils.isBlank(siteId)) {
            return Collections.emptyList();
        }

        // 栏目ID不为空则只获取本栏目关键词
        final boolean onlyThisColumn = org.apache.commons.lang3.StringUtils.isNotBlank(columnId);

        CmsColumn curColumn = onlyThisColumn ? getColumnById(columnId) : null;
        String paramConfig = null != curColumn ? curColumn.getParamConfig() : "";
        paramConfig = org.apache.commons.lang3.StringUtils.defaultIfBlank(paramConfig, CmsUtils.getSiteTheme(siteId).getParamConfig());

        // 默认需要返回的关键词数量
        Integer contentsKeywordCount = (Integer) CmsUtils.getParamConfig(CmsConstant.THEME_PARAM_CONTENTS_KEYWORD_COUNT_KEY, paramConfig);
        if (contentsKeywordCount == null || contentsKeywordCount == 0) {
            contentsKeywordCount = CmsConstant.THEME_PARAM_CONTENTS_KEYWORD_COUNT_VAL;
        }

        // 获取关键词并排序
        List<String> keywordsList = CmsCacheUtils.getContentListByCache(siteId)
                .stream()
                .filter(item -> {
                    boolean sameSite = siteId.equals(item.getSiteId());
                    return onlyThisColumn ? sameSite && columnId.equals(item.getColumnId()) : sameSite;
                })
                .sorted(HITS_COMPARATOR)
                .map(item -> org.apache.commons.lang3.StringUtils.trimToEmpty(item.getKeywords()))
                .distinct()
                .collect(Collectors.toList());


        // 获取指定数量的关键词
        List<String> resultList = new ArrayList<>(contentsKeywordCount + 6);
        for (String keywords : keywordsList) {
            List<String> tempKeywordList = KEYWORDS_SPLITTER.splitToList(keywords);
            resultList.addAll(tempKeywordList);
            if (resultList.size() >= contentsKeywordCount) {
                break;
            }
        }

        // addAll有可能导致数量大于contentsKeywordCount,所以这里需要截取
        return resultList.size() > contentsKeywordCount ? resultList.subList(0, contentsKeywordCount) : resultList;
    }


    /**
     * 获取热门内容列表
     *
     * @param siteId   网站id
     * @param columnId 栏目ID，不为空则只获取本栏目的热门内容
     * @return list
     */
    public static List<CmsContents> getHotContentsList(final String siteId, final String columnId) {
        if (org.apache.commons.lang3.StringUtils.isBlank(siteId)) {
            return Collections.emptyList();
        }

        // 栏目ID不为空则只获取本栏目关键词
        final boolean onlyThisColumn = org.apache.commons.lang3.StringUtils.isNotBlank(columnId);

        CmsColumn curColumn = onlyThisColumn ? getColumnById(columnId) : null;
        String paramConfig = null != curColumn ? curColumn.getParamConfig() : "";
        paramConfig = org.apache.commons.lang3.StringUtils.defaultIfBlank(paramConfig, CmsUtils.getSiteTheme(siteId).getParamConfig());

        // 默认需要返回的关键词数量
        Integer hotContentsCount = (Integer) CmsUtils.getParamConfig(CmsConstant.THEME_PARAM_HOT_CONTENTS_COUNT_KEY, paramConfig);
        if (hotContentsCount == null || hotContentsCount == 0) {
            hotContentsCount = CmsConstant.THEME_PARAM_HOT_CONTENTS_COUNT_VAL;
        }

        // 获取内容并排序
        List<CmsContents> contentsList = CmsCacheUtils.getContentListByCache(siteId)
                .stream()
                .filter(item -> {
                    boolean sameSite = siteId.equals(item.getSiteId());
                    return onlyThisColumn ? sameSite && columnId.equals(item.getColumnId()) : sameSite;
                }).sorted(HITS_COMPARATOR).collect(Collectors.toList());
        return contentsList.size() > hotContentsCount ? contentsList.subList(0, hotContentsCount) : contentsList;
    }

    /**
     * 获取内容排行列表
     *
     * @param isPreview 是否预览
     * @param columnId  栏目ID，不为空则只获取本栏目推荐内容
     * @return list
     */
//    public static List<CmsContents> getRecommendList(String isPreview, final String columnId, String siteId) {
//        // 获取recomCount
//        Integer recommendCount = (Integer) CmsUtils.getParamConfig("recomCount", CmsUtils.getSiteTheme(siteId).getParamConfig());
//        if (recommendCount == null || recommendCount == 0) {
//            recommendCount = CmsConstant.THEME_PARAM_PAGE_SIZE_VAL;
//        }
//
//        // 更新过期权重
//        contentsService.updateExpiredWeightToReq();
//
//        Predicate<CmsContents> predicate = null;
//        // 如果columnId不为空则需要增加栏目的判断
//        if (org.apache.commons.lang3.StringUtils.isNotBlank(columnId)) {
//            predicate = item -> {
//                if (!CmsConstant.YES.equals(item.getRecomFlag())) {
//                    return false;
//                }
//                return columnId.equals(item.getColumnId());
//            };
//        } else {
//            predicate = item -> CmsConstant.YES.equals(item.getRecomFlag());
//        }
//
//        List<CmsContents> contentsList = getContentListByCache().stream().filter(predicate).collect(Collectors.toList());
//        return contentsList.size() > recommendCount ? contentsList.subList(0, recommendCount) : contentsList;
//    }

    /**
     * 获取在首页显示的栏目列表
     *
     * @param siteId      站点id
     * @param modelEnName 模型英文名称
     * @return list
     */
    public static List<CmsColumn> getHomeShowColumnList(final String siteId, final String modelEnName) {
        if (org.apache.commons.lang3.StringUtils.isAnyBlank(siteId, modelEnName)) {
            return Collections.emptyList();
        }

        return CmsCacheUtils.getColumnListByCache(siteId).stream().filter((column) -> {
            if (!siteId.equals(column.getSiteId())) {
                return false;
            }


            // 获取模型
            if (null == column.getModel() || null == column.getModel().getId()) {
                return false;
            }

            CmsModel model = getModelById(column.getModel().getId());
            if (null == model) {
                return false;
            }

            boolean isHomeModel = modelEnName.equals(model.getEnname())
                    && CmsConstant.YES.equals(model.getHomeFlag());
            if (!isHomeModel) {
                return false;
            }

            return CmsConstant.YES.equals(column.getHomeFlag()) && !column.getHasChildren();
        }).collect(Collectors.toList());
    }

    /**
     * 获取在首页显示的内容列表
     *
     * @param columnId 栏目编号
     * @return list
     */
    public static List<CmsContents> getHomeShowContentsList(final String siteId, final String columnId) {
        // 根据siteId找到对应的主题配置
        CmsThemes theme = getSiteTheme(siteId);

        CmsColumn curColumn = getColumnById(columnId);
        String paramConfig = null != curColumn ? curColumn.getParamConfig() : "";
        paramConfig = org.apache.commons.lang3.StringUtils.defaultIfBlank(paramConfig, CmsUtils.getSiteTheme(siteId).getParamConfig());

        Integer colShowCount = (Integer) CmsUtils.getParamConfig(CmsConstant.THEME_PARAM_COL_SHOW_COUNT_KEY, paramConfig);
        if (colShowCount == null || colShowCount == 0) {
            colShowCount = CmsConstant.THEME_PARAM_COL_SHOW_COUNT_VAL;
        }

        //更新过期权重
        contentsService.updateExpiredWeightToReq();
        List<CmsContents> contentsList = CmsCacheUtils.getContentListByCache(siteId).stream()
                .filter(item -> columnId.equals(item.getColumnId()) && CmsConstant.YES.equals(item.getRecomFlag()))
                .collect(Collectors.toList());
        return contentsList.size() > colShowCount ? contentsList.subList(0, colShowCount) : contentsList;
    }

    /**
     * 获取在首页显示的动态内容列表
     *
     * @return list
     */
    public static List<CmsContentsDyn> getHomeShowContentsDynList(final String siteId, final String columnId) {
        CmsColumn column = getColumnById(columnId);
        if (null == column) {
            return Collections.emptyList();
        }

        // 根据siteId找到对应的主题配置
        CmsThemes theme = getSiteTheme(siteId);

        String paramConfig = org.apache.commons.lang3.StringUtils.defaultIfBlank(column.getParamConfig(), CmsUtils.getSiteTheme(siteId).getParamConfig());
        Integer colShowCount = (Integer) CmsUtils.getParamConfig(CmsConstant.THEME_PARAM_COL_SHOW_COUNT_KEY, paramConfig);
        if (colShowCount == null || colShowCount == 0) {
            colShowCount = CmsConstant.THEME_PARAM_COL_SHOW_COUNT_VAL;
        }

        //更新过期权重
        contentsDynService.updateExpiredWeightToReq();
        List<CmsContentsDyn> contentsDynList = CmsCacheUtils.getContentDynListByCache(siteId).stream()
                .filter(item -> null != item.getColumn() && columnId.equals(item.getColumn().getId()))
                .collect(Collectors.toList());
        contentsDynList = contentsDynList.size() > colShowCount ? contentsDynList.subList(0, colShowCount) : contentsDynList;

        // 反序列化动态表单数据
        CmsContentsDyn contentsDyn = new CmsContentsDyn();
        contentsDyn.setColumn(column);
        contentsDyn.setReleaseDate(new Date());
        contentsDyn.setDelFlag(CmsContents.DEL_FLAG_NORMAL);
        for (int i = 0, size = contentsDynList.size(); i < size; i++) {
            contentsDyn = contentsDynList.get(i);
            dynamicService.modelFromJson(contentsDynService.getDynamic(contentsDyn).getDataModel(), contentsDyn.getMainMap(), contentsDyn.getTypeMap());
            contentsDyn.setDataMap(dynamicService.dataFromJson(contentsDyn.getData(), contentsDyn.getTypeMap()));
            if (null == contentsDyn.getDataMap()) {
                contentsDyn.setDataMap(new HashMap<>(16));
            }
        }
        return contentsDynList;

    }

    /**
     * 获取在首页轮播的内容列表
     *
     * @return list
     */
    public static List<CmsContents> getCarouselContentsList(String siteId) {
        CmsThemes theme = CmsUtils.getSiteTheme(siteId);
        Integer carouselCount = (Integer) CmsUtils.getParamConfig(CmsConstant.THEME_PARAM_CAROUSEL_COUNT_KEY, null != theme ? theme.getParamConfig() : null);
        if (carouselCount == null || carouselCount == 0) {
            carouselCount = CmsConstant.THEME_PARAM_CAROUSEL_COUNT_VAL;
        }

        CmsContents contents = new CmsContents();
        contents.setCarouselFlag(CmsConstant.YES);

        // 更新过期权重
        contentsService.updateExpiredWeightToReq();
        List<CmsContents> contentsList = CmsCacheUtils.getContentListByCache(siteId).stream()
                .filter(item -> CmsConstant.YES.equals(item.getCarouselFlag()))
                .collect(Collectors.toList());
        return contentsList.size() > carouselCount ? contentsList.subList(0, carouselCount) : contentsList;
    }

    /**
     * 获取网站总点击量
     *
     * @return int
     */
    public static int getTotalHits(final String siteId) {
        if (org.apache.commons.lang3.StringUtils.isBlank(siteId)) {
            return 0;
        }

        Integer homeHits = getHomeHits(siteId);
        Integer columnTotalHits = columnService.getTotalHitsBySiteId(siteId);
        columnTotalHits = null == columnTotalHits ? 0 : columnTotalHits;

        Integer contentTotalHits = contentsService.getTotalHitsBySiteId(siteId);
        contentTotalHits = null == contentTotalHits ? 0 : contentTotalHits;

        Integer contentDynTotalHits = contentsDynService.getTotalHitsBySiteId(siteId);
        contentDynTotalHits = null == contentDynTotalHits ? 0 : contentDynTotalHits;
        return homeHits + columnTotalHits + contentTotalHits + contentDynTotalHits;
    }

    /**
     * 获取首页点击量
     *
     * @return int
     */
    public static int getHomeHits(String siteId) {
        return siteService.getHomeHits(siteId);
    }

    /**
     * 修正文件路径
     */
    public static String correctFileUrl(String src) {
        if (StringUtils.isBlank(src) || !src.contains(CmsConstant.USERFILES_BASE_URL)) {
            return src;
        }
        if (src.startsWith(context.getContextPath() + CmsConstant.USERFILES_BASE_URL)) {
            return src;
        } else {
            return context.getContextPath() + src.substring(src.indexOf(CmsConstant.USERFILES_BASE_URL));
        }
    }

    /**
     * 对象JSON序列化
     */
    public static String toJson(Object object) {
        return JsonMapper.toJsonString(object);
    }

    /**
     * 增加参数配置属性
     *
     * @param model  Model对象
     * @param prefix Model属性名前缀
     * @param param  参数串，如{count:2,show:'yes'}
     */
    public static void addParamConfigAttribute(Model model, String prefix, String param) {
        if (StringUtils.isNotBlank(param)) {
            @SuppressWarnings("rawtypes")
            Map map = JsonMapper.getInstance().fromJson(param, Map.class);
            if (map != null) {
                for (Object o : map.keySet()) {
                    model.addAttribute(prefix + o.toString(), map.get(o));
                }
            }
        }
    }

    public static void addParamConfigAttribute(Model model, CmsColumn column) {
        List<CmsColumn> columnList = Lists.newArrayList();
        CmsColumn c = column;
        boolean goon = true;
        do {
            if (c.getParent() == null || "0".equals(c.getParent().getId())) {
                goon = false;
            }
            columnList.add(c);
            c = c.getParent();
        } while (goon);
        Collections.reverse(columnList);
        for (CmsColumn ca : columnList) {
            addParamConfigAttribute(model, CmsUtils.COLUMN_PARAM_CONFIG_PREFIX, ca.getParamConfig());
        }
    }

    /**
     * 获取参数配置属性
     *
     * @param key   参数key
     * @param param 参数串，如{count:2,show:'yes'}
     */
    public static Object getParamConfig(String key, String param) {
        if (StringUtils.isNotBlank(param)) {
            @SuppressWarnings("rawtypes")
            Map map = JsonMapper.getInstance().fromJson(param, Map.class);
            if (null != map) {
                return map.get(key);
            }
        }
        return null;
    }
}
